package main

import (
	"API/routers"
	"common/config"
	"common/initialize"
	"context"
	"errors"
	"log"
	"net/http"
	_ "net/http/pprof" // 导入 pprof 包
	"os"
	"os/signal"
	"time"

	"github.com/gin-gonic/gin"
)

func main() {
	config.InitViper()
	initialize.InitNachos(func() {

	})
	r := gin.Default()

	// CORS中间件，允许所有跨域
	r.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, x-token")
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}
		c.Next()
	})

	r.Use(gin.Logger())
	r.Use(gin.Recovery())

	routers.InitUserRouter(r)
	srv := &http.Server{
		Addr:    ":8080",
		Handler: r,
	}

	// 启动主HTTP服务
	go func() {
		// 服务连接
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatalf("listen: %s\n", err)
		}
	}()

	// 启动 pprof 服务
	go func() {
		log.Println("Starting pprof server on :6060")
		if err := http.ListenAndServe(":6060", nil); err != nil {
			log.Printf("Failed to start pprof server: %v", err)
		}
	}()

	// 等待中断信号以优雅地关闭服务器（设置 5 秒的超时时间）
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt)
	<-quit
	log.Println("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown:", err)
	}
	log.Println("Server exiting")
}
